package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.basic.model.Company;
import com.sangmo.fts.basic.service.CompanyService;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.process.storage.interfaces.CsfAssuranceCreation;
import com.sangmo.fts.process.storage.model.CsfAssurance;
import com.sangmo.fts.process.storage.model.CsfLoan;
import com.sangmo.fts.process.storage.repo.CsfAssuranceRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Transactional
public class CsfAssuranceEntityService extends AuthorityEntityService<CsfAssurance> {

    @Autowired
    private CsfAssuranceRepo csfAssuranceRepo;

    @Autowired
    private CsfLoanService csfLoanService;

    @Autowired
    private CsfContractService csfContractService;

    @Autowired
    private CompanyService companyService;

    @Override
    protected IDataViewRepo<CsfAssurance> getRepo() {
        return csfAssuranceRepo;
    }

    @Override
    protected void onCreate(CsfAssurance entity, Object bo) {
        super.onCreate(entity, bo);
        CsfAssuranceCreation creation = (CsfAssuranceCreation) bo;
        CsfLoan loan = csfLoanService.get(creation.getLoanId());
        entity.setVoucheeId(loan.getApplyId());
        entity.setBankId(loan.getBankId());
        entity.setContractAmount(csfContractService.calculateContractAmount(loan.getContractId()));
//        CompanyAnn company = companyService.get(loan.getApplyId());
//        BigDecimal ratio = CompanyAnn.CreditRatingTypes.get(company.getCreditRating());
//        BigDecimal deposit = loan.getAmount().multiply(ratio).setScale(2, BigDecimal.ROUND_HALF_UP);
        entity.setAmount(loan.getAmount().subtract(loan.getDeposit()));
        entity.setEndDate(loan.getEndTime());
    }

    protected void buyerConfirm(CsfAssurance entity) {
        entity.setBuyerConfirm(true);
        this.save(entity);
    }

}
